package service.Impl;


import enmu.ItemType;
import enmu.OrderStatus;
import exception.BusinessException;
import exception.ExceptionCode;
import model.Item;
import model.Order;
import service.IOrderRepositoryService;
import service.IOrderService;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.stream.Collectors;


public class OrderServiceImpl implements IOrderService {
    IOrderRepositoryService orderRepositoryService = new OrderRepositoryServiceImpl();

    @Override
    public Order createOrder(List<Item> items, boolean isVIP, LocalDateTime currenTime) throws BusinessException {
        /**
         * 订单不能为空
         */
        if (items == null || items.isEmpty()){
            throw new BusinessException(ExceptionCode.EMPTY);
        }
        /**
         * 主食必须有
         */
        boolean trymain = false;
        boolean drink = false;
        boolean dessert = false;
        for (Item item:items) {
            if (item.getType()==ItemType.MAIN){
                trymain = true;
            }
            if (item.getType()==ItemType.DRINK){
                drink = true;
            }
            if (item.getType()==ItemType.DESSERT){
                dessert = true;
            }
        }
        if (!trymain){
            throw new BusinessException(ExceptionCode.NO_MAIN_FOOD);
        }
        if (!trymain && !drink && dessert){
            throw new BusinessException(ExceptionCode.DESSERT_ALONE);
        }
        /**
         * 获取当前时间判断时间是否在符合范围中
         */
        LocalTime now = currenTime.toLocalTime();
        List<Item> filterTimeItems = filterTimeSensitiveItems(items, now);
       if (filterTimeItems.equals("")){
           throw new BusinessException(ExceptionCode.ITEM_INVALID);
       }
        /**
         * 总价
         */
        double price = promotion(filterTimeItems,isVIP);
        /**
         * 商品数量 <=5
         */
        if (filterTimeItems.size() > 5){
            throw new BusinessException(ExceptionCode.TOO_MANY_ITEMS);
        }
        //创建订单
        Order resorder = new Order();
        resorder.setOrderId("55");
        resorder.setItems(filterTimeItems);
        resorder.setStatus(OrderStatus.CREATED);
        resorder.setTotalPrice(price);
        resorder.setCreateTime(currenTime);
        orderRepositoryService.save(resorder);
        return resorder;
    }

    @Override
    public void cancelOrder(String orderId, LocalDateTime currentTime) throws BusinessException {
        Order order = orderRepositoryService.findById(orderId);
        if (order == null){
            throw new BusinessException(ExceptionCode.EMPTY);
        }
        if (order.getStatus() == OrderStatus.PAID) {
            throw new BusinessException(ExceptionCode.PAID_ORDERS);
        }
        /**
         * 获取订单中的时间并增加30minute(分钟)与传入的时间对比是否在它之前
         *
         */
        if (order.getCreateTime().plusMinutes(30).isBefore(currentTime)){
            orderRepositoryService.updateStatus(orderId,OrderStatus.CANCELLED);
        }else {
            throw new BusinessException(ExceptionCode.ORDERS_30MINUTE);
        }
    }


    // 筛选时间敏感项目
    private List<Item> filterTimeSensitiveItems(List<Item> items, LocalTime currentTime) {
        List<Item> filtered = items.stream()
                .filter(item -> !"冰咖啡".equals(item.getName()) ||
                        currentTime.isBefore(LocalTime.of(15, 0)))
                .collect(Collectors.toList());

        if (filtered.size() < items.size()) {
            // 可以添加日志记录或设置订单备注
            System.out.println("已过滤" + (items.size() - filtered.size()) + "件时间敏感商品,已下架");
        }
        return filtered;
    }
    //促销规则
    private double promotion(List<Item> items, boolean isVIP){
        // 计算非饮料商品的总价
        double nonDrinkPrice = items.stream()
                .filter(i -> i.getType() != ItemType.DRINK)
                .mapToDouble(Item::getPrice)
                .sum();
        //计算饮料类商品促销后总价
        double drinkprice = items.stream()
                .filter(i -> i.getType() == ItemType.DRINK)
                .collect(Collectors.groupingBy(Item::getId, Collectors.toList()))
                .values().stream()
                .mapToDouble(list -> {
                    double price = list.get(0).getPrice();
                    int count = list.size();
                    return (Math.ceil(count / 2.0) * price + (count / 2) * price * 0.5);
                })
                .sum();
        //合并价格
        double resultprice = nonDrinkPrice + drinkprice;
        // 检查是否包含汉堡和薯条
        boolean hasBurger = items.stream().anyMatch(i -> i.getName().equals("汉堡"));
        boolean hasFries = items.stream().anyMatch(i -> i.getName().equals("薯条"));
        if (hasBurger && hasFries) {
            resultprice = resultprice - 15 -15 + 25;
        }
        //是否为VIP(9折)
        if (isVIP){
            resultprice *=0.9;
        }

        return resultprice;
    }

}